import 'package:eshi/app/settings/AppLocalizations.dart';
import 'package:eshi/app/shi/data/System.dart';
import 'package:flutter/material.dart';
import 'package:eshi/main.dart';
import 'package:url_launcher/url_launcher.dart';

/// 底部显示消息 
msg(String str,{bgColor=Colors.green,sec=2}){
  final context = mainWidgetKey.currentContext;
  // 在 Scaffold 中调用
  ScaffoldMessenger.of(context!).showSnackBar(
    SnackBar(
      content: Text(str), // 提示文本
      duration: Duration(seconds: sec), // 显示时长（默认4秒）
      action: SnackBarAction(
        label: '', // 可选操作按钮
        onPressed: () {
          // 点击撤销的逻辑
        },
      ),
      backgroundColor: bgColor, // 背景色
    ),
  );
}
msgErr(String str){
  msg(mt(str),bgColor: Colors.blueGrey,sec:5);
}

//确认框
Future<bool> confirm({title="确认操作",msg="你确定要执行吗？"}) async {
  return await showDialog(context: System.context, builder: (context) => AlertDialog(
      title: mText(title),
      content: mText(msg),
      actions: [
        // 取消按钮
        TextButton(
          onPressed: () {
            Navigator.pop(context,false); // 关闭对话框
          },
          child: mText('取消'),
        ),
        // 确认按钮
        TextButton(
          onPressed: () {
            Navigator.pop(context,true); // 关闭对话框
          },
          child: mText('确认'),
        ),
      ],
    ),
  );
}

//简单输入框  
prompt(String name,onChange,{title="请输入",message="",hintText="请输入内容",Widget? suffixIcon}){
   var controller = TextEditingController();
   if(name.isNotEmpty){
     controller.value = TextEditingValue(
        text: name,
        selection: TextSelection(
          baseOffset:  0,
          extentOffset: name.length
        )
      );
   }
   showDialog(context: System.context, builder: (context) => AlertDialog(
      title: mText(title),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (message.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(bottom: 8.0),
              child: mText(message),
            ),
          TextField(
            controller: controller,
            autofocus: true, // 自动获取焦点
            decoration:  InputDecoration(
              border: OutlineInputBorder(),
              hintText: mt("请输入内容"),
              suffixIcon: IconButton(
                  icon: const Icon(Icons.close),
                  onPressed:(){
                    controller.text="";
                  },
              ),
            ),
            
            onSubmitted: (value) {
              // 按回车直接确认
              onChange(value);
              Navigator.pop(context, value);
            },
          ),
        ],
      ),
      actions: [
        // 取消按钮
        TextButton(
          onPressed: () {
            Navigator.pop(context); // 关闭对话框
          },
          child: mText('取消'),
        ),
        // 确认按钮
        TextButton(
          onPressed: () {
            Navigator.pop(context); // 关闭对话框
            onChange(controller.text); // 回调通知确认
          },
          child:  mText('确认'),
        ),
      ],
    ),
  );
}

String mt(zh){
  return AppLocalizations.t(zh);
}

class mText extends Text {
  mText(String data,{
    super.key,
    super.style,
    super.strutStyle,
    super.textAlign,
    super.textDirection,
    super.locale,
    super.softWrap,
    super.overflow,
    @Deprecated(
      'Use textScaler instead. '
      'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. '
      'super feature was deprecated after v3.12.0-2.0.pre.',
    )
    super.textScaleFactor,
    super.textScaler,
    super.maxLines,
    super.semanticsLabel,
    super.semanticsIdentifier,
    super.textWidthBasis,
    super.textHeightBehavior,
    super.selectionColor,
  }) : super(mt(data));
}

  T whenBool <T>(bool s,T a,T b){
    return s?a:b;
  }

  setTimeout(void Function() handler, int ms) async {
      await  Future.delayed(Duration(milliseconds: ms));
      handler();
  }

  final Map<String,List<int>> stringRunMap= {};
  stringRun(int ms,void Function() handler){
      final rid = handler.hashCode.toString();
      final List<int> queue = stringRunMap.containsKey(rid) ? stringRunMap[rid] as List<int>: <int>[];
      queue.add(DateTime.now().millisecondsSinceEpoch);
      stringRunMap[rid] =queue;
      setTimeout((){
        final List<int> queue = stringRunMap[rid] as List<int>;
        queue.removeAt(0);
        if(queue.isEmpty){
          handler();
        }
      },ms);
  }

  void openUrl(String url) async {
    if (await canLaunchUrl(Uri.parse(url))) {
      await launchUrl(Uri.parse(url));
    }
  }